package gomod

import (
	"debug/buildinfo"
	"fmt"
	"runtime/debug"
)

// PrintOwnBuildInfo 输出go build的mod信息
func PrintOwnBuildInfo() {
	if info, ok := debug.ReadBuildInfo(); ok {
		fmt.Println("Current Execute Binary Compiled with Go version:", info.GoVersion)
		fmt.Println("Main module:")
		printModule(&info.Main)
		fmt.Println("Dependencies:")
		for _, dep := range info.Deps {
			printModule(dep)
		}
	}
}

// PrintGoBuildInfo 输出go build的mod信息
func PrintGoBuildInfo(file string) {
	if info, err := buildinfo.ReadFile(file); err == nil {
		fmt.Println("Go buildid:", loadGoBuildId(file))
		fmt.Println("Compiled with Go version:", info.GoVersion)
		fmt.Println("Main module:")
		printModule(&info.Main)
		fmt.Println("Dependencies:")
		for _, dep := range info.Deps {
			printModule(dep)
		}
	}
}

func loadGoBuildId(file string) string {
	return ""
}

func printModule(m *debug.Module) {
	fmt.Printf("\t%s", m.Path)
	if m.Version != "(devel)" {
		fmt.Printf("@%s", m.Version)
	}
	if m.Sum != "" {
		fmt.Printf(" (sum: %s)", m.Sum)
	}
	if m.Replace != nil {
		fmt.Printf(" (replace: %s)", m.Replace.Path)
	}
	fmt.Println()
}
